package com.architecture.core.service.associate;

import com.architecture.core.entity.Permission;
import com.architecture.core.entity.Resource;
import com.architecture.core.except.ErrException;
import com.architecture.core.service.AbstractService;
import com.architecture.core.utils.ErrCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: aguang
 * Date: 13-1-21
 * Time: 下午6:13
 * To change this template use File | Settings | File Templates.
 */
@Service("managePermissionService")
public class PermissionAssociateService extends AbstractService {

    public void associateResource(String permissionId, String resourceId) throws ErrException {

        if (StringUtils.isBlank(permissionId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        if (StringUtils.isBlank(resourceId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        Permission permission = (Permission) super.baseDAO.findUnique(Permission.class, permissionId);

        Resource resource = (Resource) super.baseDAO.findUnique(Resource.class, resourceId);

        permission.getResourceList().add(resource);
        resource.getPermissionList().add(permission);

        this.baseDAO.update(permission);
        this.baseDAO.update(resource);

    }

    public void associateResource(String permissionId, List<String> resourceIdList) throws ErrException {

        if (CollectionUtils.isEmpty(resourceIdList)) {
            throw new ErrException(ErrCode.EMPTY_COLLECTION);
        }

        for (String resourceId : resourceIdList) {
            this.associateResource(permissionId, resourceId);
        }
    }

    public void deassociateResource(String permissionId, String resourceId) throws ErrException {
        if (StringUtils.isBlank(permissionId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        if (StringUtils.isBlank(resourceId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        Permission permission = (Permission) super.baseDAO.findUnique(Permission.class, permissionId);

        Resource resource = (Resource) super.baseDAO.findUnique(Resource.class, resourceId);

        permission.getResourceList().remove(resource);
        resource.getPermissionList().remove(permission);

        this.baseDAO.update(permission);
        this.baseDAO.update(resource);
    }

    public void deassociateResource(String permissionId, List<String> resourceIdList) throws ErrException {
        if (CollectionUtils.isEmpty(resourceIdList)) {
            throw new ErrException(ErrCode.EMPTY_COLLECTION);
        }

        for (String resourceId : resourceIdList) {
            this.deassociateResource(permissionId, resourceId);
        }
    }

}
